package com.hong.utils.semaphore;

import java.util.Collection;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: Administrator
 * @Date: 2018/7/23 12:15
 * @Description:
 */
public class SemaphoreExample4 {
    public static void main(String[] args) throws InterruptedException {
        final MySemaphore semaphore = new MySemaphore(5);

        Thread t1  = new Thread(){
            @Override
            public void run() {
                try {
                    /*获取并返回所有可立即获得的许可证。 */
                    semaphore.drainPermits();
                    /*返回此信号量中当前可用的许可数。*/
                    System.out.println(semaphore.availablePermits());
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release(5);
                }
                System.out.println("T1 finished.");
            }
        };
        t1.start();
        TimeUnit.SECONDS.sleep(1);
        Thread t2  = new Thread(){
            @Override
            public void run() {
                try {
                    semaphore.tryAcquire();
                }finally {
                    semaphore.release();
                }
                System.out.println("T2 finished.");
            }
        };

        t2.start();
        TimeUnit.SECONDS.sleep(1);
        /*查询线程是否有等待获取*/
        boolean bool = semaphore.hasQueuedThreads();
        System.out.println(bool);
        Collection<Thread> waitingThreads = semaphore.getWaitingThreads();
        for(Thread t :waitingThreads){
            System.out.println(t);
        }

    }

    static class MySemaphore extends Semaphore{
        MySemaphore(int permits){
            super(permits);
        }
        MySemaphore(int permits,boolean fair){
            super(permits,fair);
            super.getQueuedThreads();
        }

        public Collection<Thread> getWaitingThreads(){
            return  super.getQueuedThreads();
        }
    }

}
